require 'fileutils'
class FilesController < ApplicationController
  before_filter :check_authorization,:except=>[:save,:refresh]
  layout 'project'
  # GET /files
  # GET /files.xml
  def index
    #permission setting
   if @project.use_permission
    
     #user has permission

       filter_sql = filter_sql(@project,"fs")

       logger.error "-----------------------------------" 
       logger.error filter_sql
       logger.error "-----------------------------------" 

       if params[:category_id].to_i > 0
          if @cur_user.has_permission?("prj_" + @project.id.to_s + "_" + params[:category_id].to_s + "_fs_cat_view")
            @file_pages, @files= paginate :files, :class_name => 'Files', :per_page => 10, :conditions=>["project_id = ? and category_id = ? ",params[:project_id], params[:category_id]],:order => "id desc"
          else
            @file_pages, @files= paginate :files,:class_name => 'Files', :per_page => 10, :conditions=>["project_id = ? and (user_id = ? and category_id = ?) ",@project.id, @cur_user.id,params[:category_id]],:order => "id desc"
          end
       elsif params[:category_id] == "uncat"
          if @cur_user.has_permission?("prj_" + @project.id.to_s + "_unc_fs_cat_view")
            @file_pages, @files= paginate :files, :class_name => 'Files',:per_page => 10, :conditions=>["project_id = ? and (category_id is null or category_id = 0)",@project.id],:order => "id desc"
          else
            @file_pages, @files= paginate :files, :class_name => 'Files', :per_page => 10, :conditions=>["project_id = ? and (user_id = ? and (category_id is null or category_id = 0))",@project.id, @cur_user.id],:order => "id desc"
          end
       else
          @file_pages, @files= paginate :files, :class_name => 'Files', :per_page => 10,:conditions=>["(project_id = ? and (#{filter_sql}) ) or (project_id= ? and user_id = #{@cur_user.id})",@project.id,@project.id],:order => "id desc"
       end
  else
    if params[:category_id].to_i > 0
      @file_pages, @files = paginate :files, :class_name => 'Files', :per_page => 10, :conditions=>["project_id = ? and category_id = ? and session_id = ''",params[:project_id], params[:category_id]],:order => "id desc"
    elsif params[:category_id] == "uncat"
      @file_pages, @files = paginate :files, :class_name => 'Files', :per_page => 10, :conditions=>["project_id = ? and (category_id = 0 or category_id is null) and session_id = ''",params[:project_id]],:order => "id desc"
    else
      @file_pages, @files = paginate :files, :class_name => 'Files', :per_page => 10, :conditions=>["project_id = ? and session_id = ''",params[:project_id]],:order => "id desc"
    end
  end

    respond_to do |format|
      format.html # index.rhtml
      format.xml  { render :xml => @files.to_xml }
    end
  end

  def save
    uni_id = params[:uni_id]

   if file = params[:Filedata]
     record_name = file.original_filename
     ext = File.extname(file.original_filename)

     #record file in db
     file_rc = Files.new
     file_rc.session_id = CGI.unescape(uni_id)
     file_rc.name = record_name
     file_rc.content_type = record_name.split(".").last
     file_rc.ext = ext
     file_rc.size = file.size
     file_rc.save
     end

     save_name = file_rc.id.to_s + ext

    #create folder if not exist
    if not File.exist?("#{RAILS_ROOT}/public/files/#{params[:pid]}")
      Dir.mkdir("#{RAILS_ROOT}/public/files/#{params[:pid]}",0777)
    end
    #save file
    f = File.new("#{RAILS_ROOT}/public/files/#{params[:pid]}/" + save_name,"w")
    f.write(file.read)
    f.close
    

    render :update do |page|
    page.visual_effect :highlight,'file_rc_' + file_rc.id.to_s
    end
  end

  def refresh
    @cats = Category.find(:all, :order=>'id desc',:conditions => ["label = ? and project_id = ?",params[:label],params[:project_id]])
    render :partial=>'files/uploaded_files',:locals=>{:uni_id=>CGI.unescape(params[:uni_id]),:label=>params[:label]}
  end

  # GET /files/1
  # GET /files/1.xml
  def show_back
    @files = Files.find(params[:id])

    respond_to do |format|
      format.html # show.rhtml
      format.xml  { render :xml => @files.to_xml }
    end
  end

  # GET /files/new
  def new
    @files = Files.new
    session[:up_files] = []
    @msg_cats = Project.find(params[:project_id]).file_categories
    redirect_to nopermission_project_permission_path(@project) if @project.use_permission and ((@project.file_categories.select{|c| @cur_user.has_permission?("prj_" + @project.id.to_s + "_#{c.id}_fs_cat_new")}.size == 0) and (not (@cur_user.has_permission?("prj_" + @project.id.to_s + "_unc_fs_cat_new"))))
  end

  # GET /files/1;edit
  def edit
    @files = Files.find(params[:id])
  end

  # POST /files
  # POST /files.xml
  def create

        file_rcs = Files.find(:all,:conditions=>["session_id = ?",CGI.unescape(session.session_id)]) 
	file_ids = params[:file_ids]
	file_category_ids = params[:file_category_ids]
        @files = [] 
	file_rcs.each_with_index do |f_rc,i|
	  if file_ids.has_key?("#{i}")
	    f_rc.session_id = ""
	    f_rc.project_id = params[:project_id]
	    f_rc.user_id    = @cur_user.id
	    f_rc.category_id = file_category_ids["#{i}"].first.to_i
	    f_rc.save
	    @files << f_rc
	  else
	    f_rc.destroy
	  end
	end

    unless params[:notify_id].nil? and @files.size > 0
      if params[:notify_id] and params[:notify_id].size > 0
      #user_list = User.find(:all,:conditions => "id in (#{params[:notify_id].join(",")})").select{|a| (not a.email.nil?) and a.email.match("@")}.collect{|u| u.email}.join(",") 
      user_emails= User.find(:all,:conditions => "id in (#{params[:notify_id].join(",")})").select{|a| (not a.email.nil?) and a.email.match("@")}.collect{|u| u.email}
      #send user mail
      #Notifier.deliver_notify('new_file',user_list,@files,@cur_user.lang)
      user_emails.each do |email|
        Notifier.deliver_notify('new_file',email,@files,@cur_user.lang)
      end
      end
    end

        flash[:notice] = ""
    respond_to do |format|
        format.html { 
	 render :update do |page|
	 page.visual_effect :highlight,'please_wait'
	 page.redirect_to project_files_path(params[:project_id])
	 end
	}
        format.xml  { head :created, :location => project_files_path(@files) }
    end
  end

  # PUT /files/1
  # PUT /files/1.xml
  def update
    @files = Files.find(params[:id])

    respond_to do |format|
      if @files.update_attributes(params[:files])
        flash[:notice] = 'Files was successfully updated.'
        format.html { redirect_to project_files_path(@files) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @files.errors.to_xml }
      end
    end
  end
                                  
  # DELETE /files/1
  # DELETE /files/1.xml
  def destroy
    @files = Files.find(params[:id])
    begin
     if file.ext;
       FileUtils.remove RAILS_ROOT + "/public/files/#{file.project.id}/" + file.id.to_s + file.ext 
     else
       FileUtils.remove "#{RAILS_ROOT}/public/files/#{@files.project.id}/#{@files.name}"
     end
    rescue 
    end
    @files.destroy
    respond_to do |format|
      format.html { redirect_to project_files_path}
      format.xml  { head :ok }
    end
  end
  def show

    file = Files.find(params[:id])

    if @project.use_permission and (not @cur_user.has_permission?("prj_" + file.project.id.to_s + "_" +  (file.category_id.to_i > 0 ? file.category_id.to_s : "unc") + "_fs_cat_view")) and file.user_id != @cur_user.id 
      redirect_to nopermission_project_permission_path(@project) 
    else

      path= RAILS_ROOT + "/public/files/#{file.project.id}/" + file.name;
      path= RAILS_ROOT + "/public/files/#{file.project.id}/" + file.id.to_s + file.ext if file.ext;
      if request.user_agent.to_s.match("MSIE")
        is_ie = true
      else
        is_ie = false 
      end
      send_file( path,
                :filename      => (is_ie ? CGI.escape(file.name) : file.name), 
   	        :type          => file.name.split(".").last ,
	        :disposition   => 'attachment',
	        :streaming      => true,
	        :buffer_size   => 2096)
   
    end
  end
end
                                  
